<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Auth;
class CartController extends Controller
{
	/**
	 * 购物车商品添加操作
	 */
    public function insert(Request $request,$id)
    {
        if(Auth::check()){
    	    $uid = Auth::user()->id;
            $res = DB::table('cart')->where('users_id','=',$uid)->where('goods_id','=',$id)->first(); 
            if($res){
                $num = $res->num+1;
                DB::table('cart')->where('users_id','=',$uid)->where('goods_id','=',$id)->update(['num'=>$num]);
            }else{       
                $data['users_id'] = $uid;
                $data['goods_id'] = $id;
                DB::table('cart')->insert($data);
            }
            return redirect('/cart');
        }
        return redirect('/auth/login');
    	//
    	
    }
    
    public function delete(Request $request)
    {
    	//获取id
    	$id = $request->input('id');
    	//获取session中的购物车信息
    	$goods = session('cart');
    	//遍历
    	foreach($goods as $k=>$v) {
    		if($v['id'] == $id) {
    			//删除当前这个session中的值
    			$request->session()->forget('cart.'.$k);
                //如果当前匹配成功 并将session删除之后 返给客户端一个 '1'
                return '1';
    		}
    	}
        return '0';
    }

    
}
